package com.wngbms;

import java.io.*;
import java.lang.reflect.MalformedParameterizedTypeException;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;

public class OSFileIODemo {
    static String path = "/root/iodemo/out.txt";
    static byte[] data = "hello windows".getBytes(StandardCharsets.UTF_8);

    public static void main(String[] args) throws IOException, InterruptedException {
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            System.out.println("end ");
        }));

        switch (args[0]) {
            case "0":
                testBasicFileIO(args[1]);
                break;
            case "1":
                testBufferdFileIO(args[1]);
                break;
            case "2":
                testRandomAccessFileWrite();
                break;
            case "3":
                break;
        }
    }

    private static void testRandomAccessFileWrite() throws IOException {

        RandomAccessFile rf = new RandomAccessFile(path, "rw");

        rf.write("hello_windows11\n".getBytes(StandardCharsets.UTF_8));
        rf.write("hello_Apple\n".getBytes(StandardCharsets.UTF_8));

        System.out.println("write....");
        System.in.read();

        rf.seek(4);
        rf.write("sony_head\n".getBytes(StandardCharsets.UTF_8));

        System.out.println("seed write ...");
        System.in.read();

        FileChannel fileChannel = rf.getChannel();
        MappedByteBuffer map = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, 4096);
        map.put("xiaomi\n".getBytes(StandardCharsets.UTF_8)); // 不是系统调用, 但数据会到底系统内核page cache
        System.out.println("map put....");
        System.in.read();

//        map.force();
        rf.seek(0);

        ByteBuffer buffer = ByteBuffer.allocateDirect(4096);
        int read = fileChannel.read(buffer);
        System.out.println(buffer);
        buffer.flip();
        System.out.println(buffer);

        for (int i = 0; i < buffer.limit(); i++) {
            System.out.print((char) buffer.get(i));
        }
    }

    private static void testBufferdFileIO(String s) throws IOException, InterruptedException {
        File file = new File(path);
        BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(file));
        while (true) {
            Thread.sleep(5);
            fos.write(data);
            if ("f".equals(s)) {
                fos.flush();
            }
        }
    }

    private static void testBasicFileIO(String s) throws IOException {
        File file = new File(path);
        FileOutputStream fos = new FileOutputStream(file);
        while (true) {
            try {
                Thread.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            fos.write(data);
            if ("f".equals(s)) {
                fos.flush();
            }
        }
    }

}
